/*
 * @Author: Liz.Zheng
 * @Date: 2021-09-29 11:55:00
 * @LastEditTime: 2023-02-22 11:30:52
 * @LastEditors: 郑亚莉 zhengyali@shequ.life
 * @Description: 请求方法封装
 * @Motto: Write the code. Change the world.
 */
import axios from "axios";
import { notification, message } from "ant-design-vue";
import shareds from "@/common/utils/shared";
import { t } from "../../locale";
import defaultSetting from "@/common/utils/defaultSetting";
let BASE_URL = defaultSetting.requestDomain;

if (process.env.NODE_ENV === "development") {
  if (window.__MICRO_APP_ENVIRONMENT__) {
    BASE_URL = BASE_URL + "/api";
  } else {
    BASE_URL = BASE_URL + "/selfApi";
  }
}
// 创建axios实例
const service = axios.create({
  // API 请求的默认前缀
  baseURL: BASE_URL,
  // 请求超时时间
  timeout: 30000,
});

const fileService = axios.create({
  baseURL: BASE_URL,
  timeout: 120000,
});

/**
 * @description: 请求异常处理
 * @param {*} data 返回数据
 * @return {*}
 * @code    返回的状态码对应的类型:
 *          *1000 正常响应
 *          *1001 业务逻辑错误
 *          *1002 登录超时
 *          *1005 前端错误(缺少参数等)
 */

const errorHandler = (response) => {
  // 代码错误提示
  const errorNotification = (tip, errorLevel) => {
    if (errorLevel) {
      notification[errorLevel]({
        message: errorLevel == "warning" ? "警告" : "错误",
        description: tip,
      });
    }
  };

  if (response.data) {
    const { code, msg, errorLevel } = response.data;
    const token = shareds.getStorage("org_token");
    switch (code) {
      case 1001:
        errorNotification(msg || "接口响应错误,请检查逻辑代码等!", errorLevel);
        break;
      case 1005:
        errorNotification(msg || "前端请求错误,请检查请求参数等!", errorLevel);
        break;
      case 1002:
        if (token) {
          message.info(t("登录超时,请重新登录~"));
          shareds.clearStorage();
        }
        // 清除token,进入登录页面
        import("@/store/index").then((data) => {
          const store = data?.default;
          store.dispatch("Logout");
        })
        break;
      case 1003:
        errorNotification(msg || "权限错误!", errorLevel);
        break;
      default:
        return Promise.reject(response.data || response);
    }
  } else {
    errorNotification(t("网络请求超时，请稍后再试!"));
    return Promise.reject(response.data || response);
  }
};

// request拦截器
service.interceptors.request.use( async (config) => {
  const user_token = shareds.getStorage("user_token");
  const org_token = shareds.getStorage("org_token");
  const language = shareds.getStorage("lang");
  if (language) {
    config.headers["language"] = language;
  }
  if (org_token) {
    config.headers["org-token"] = org_token;
  } else if (user_token) {
    config.headers["user-token"] = user_token;
  }
  await import("@/store/index").then((data) => {
    const store = data?.default;
    const buildingInfo = store?.getters?.buildingInfo;
    if (buildingInfo.permissionBuildings) {
      config.headers["checked-build"] = JSON.stringify(
        buildingInfo.permissionBuildings
      );
    }
  })
  return config;
}, errorHandler);

// response拦截器
service.interceptors.response.use((response) => {
  if (response.data) {
    const { code } = response.data;
    if (code === 1000) {
      return response.data;
    }
    if (response.request.responseType == "blob") {
      let fileNameArr =
        response.headers["content-disposition"].split("filename*=UTF-8''");
      let fileName = "";
      if (fileNameArr.length > 1) {
        fileName = fileNameArr[1];
        fileName = decodeURIComponent(fileName);
      }
      return { data: response.data, fileName };
    }
  }
  let postData = undefined;
  if (response.config.data) {
    try {
      postData = JSON.parse(response.config.data)
    } catch (err) {
      postData = undefined;
    }
  }
  if (postData?.failNoMsg || response.config.params?.failNoMsg) {
    return response.data;
  } else {
    return errorHandler(response);
  }
}, errorHandler);

const request = {
  BASE_URL,
  // get请求 server微服务 url 请求地址
  get(server, url, params = {}) {
    return new Promise((resolve, reject) => {
      server = server.indexOf("/") != 0 ? `/${server}` : server;
      url = server + url;
      service
        .get(url, {
          params,
        })
        .then((res) => {
          if (params.needMsg) {
            resolve(res);
          }
          resolve(res.data);
        })
        .catch((err) => {
          reject(err);
        });
    });
  },
  //   post请求
  post(server, url, params = {}) {
    return new Promise((resolve, reject) => {
      server = server.indexOf("/") != 0 ? `/${server}` : server;
      url = server + url;
      service
        .post(url, params)
        .then((res) => {
          if (params.needMsg) {
            resolve(res);
          }
          resolve(res.data);
        })
        .catch((err) => {
          reject(err);
        });
    });
  },
  //  put请求
  put(server, url, params = {}) {
    return new Promise((resolve, reject) => {
      server = server.indexOf("/") != 0 ? `/${server}` : server;
      url = server + url;
      service
        .put(url, params)
        .then((res) => {
          if (params.needMsg) {
            resolve(res);
          }
          resolve(res.data);
        })
        .catch((err) => {
          reject(err);
        });
    });
  },
  // delete请求
  del(server, url, params = {}) {
    return new Promise((resolve, reject) => {
      server = server.indexOf("/") != 0 ? `/${server}` : server;
      url = server + url;
      service
        .delete(url, { data: params })
        .then((res) => {
          if (params.needMsg) {
            resolve(res);
          }
          resolve(res.data);
        })
        .catch((err) => {
          reject(err);
        });
    });
  },
  // 获取服务端文件内容
  getJson(url, params = {}) {
    return new Promise((resolve, reject) => {
      fileService
        .get(url, params)
        .then((res) => {
          if (res.status === 200) {
            resolve(res.data);
          } else {
            reject(err);
          }
        })
        .catch((err) => {
          reject(err);
        });
    });
  },
  // 下载downLoad
  downLoad(server, url, params = {}, contentType = "") {
    return new Promise((resolve, reject) => {
      url = server + url;
      service
        .get(url, {
          params,
          responseType: "blob",
          headers: {
            "content-type":
              contentType ||
              "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
          },
        })
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  },
};

export default request;
